<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图案</title>

    <style>
        #canvas{
            background: #eeeeee;
            border:thin solid cornflowerblue;
        }
        #radios{
            padding: 10px;
        }
    </style>
</head>
<body>
    <div id="radios">
        <input type="radio" id="repeatRadio" name="repeatRadio" checked>repeat</input>
        <input type="radio" id="repeatxRadio" name="repeatxRadio">repeat-x</input>
        <input type="radio" id="repeatYRadio" name="repeatYRadio">repeat-y</input>
        <input type="radio" id="noRepeatRadio" name="noRepeatRadio">no repeat</input>
    </div>

    <canvas id="canvas" width="450" height="275">
        升级你的浏览器
    </canvas>

    <script>
        var canvas  =   document.getElementById('canvas'),
                context =   canvas.getContext('2d'),
                repeatRadio =   document.getElementById('repeatRadio'),
                repeatXRadio =   document.getElementById('repeatXRadio'),
                repeatYRadio =   document.getElementById('repeatYRadio'),
                noRepeatRadio =   document.getElementById('noRepeatRadio'),
                image   =   new Image();
//        Function
        function fillCanvasWithPattern(repeatString){
            var pattern  =   context.createPattern(image,repeatString);
            context.clearRect(0,0,canvas.width,canvas.height);
            context.fillStyle   =   pattern;
            context.fillRect(0,0,canvas.width,canvas.height);
            context.fill();
        }
//        Event Handlers
        repeatRadio.onclick =   function(e){
            fillCanvasWithPattern('repeat');
        };
        repeatXRadio.onclick=   function(e){
            fillCanvasWithPattern('repeat-X');
        };
        repeatYRadio.onclick=   function(e){
            fillCanvasWithPattern('repeat-Y');
        };
        noRepeatRadio.onclick=  function(e){
            fillCanvasWithPattern('no-repeat');
        };
        image.src   =   'redball.png';
        image.onload=   function(e){
            fillCanvasWithPattern('repeat');
        };
    </script>
</body>
</html>